const App = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 优惠券列表
    list: [],
    // 兑换码
    code : '',
    // show
    notcont: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // 当前页面参数
    this.data.options = options;
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    // 获取优惠券列表
    this.getCouponList();
  },

  /**
   * 获取优惠券列表
   */
  getCouponList: function() {
    let _this = this;
    App._get('coupon/lists', {}, function(result) {
      _this.setData({
        list: result.data.list,
        notcont: !result.data.list.length
      });
    });
  },

  /**
   * 立即领取
   */
  receive: function(e) {
    let _this = this,
      couponId = e.currentTarget.dataset.couponId;
    App._post_form('user.coupon/receive', {
      coupon_id: couponId
    }, function(result) {
      App.showSuccess(result.msg);
      // 获取优惠券列表
      _this.getCouponList();
    });

  },
  // 开始兑换
  handleExchange(){
    let _this = this;
    var submit = true;
    if(!_this.data.code){
      App.showError('请输入兑换码');
      return false;
    }
    if(!submit){
      return false;
    }
    wx.showLoading({
      mask:true,
      title: '兑换中...',
    })
    submit = false;
    App._post_form('user.coupon/exchange', {
      code: _this.data.code
    }, function(result) {
      submit = true;
      console.log(result)
      App.showSuccess(result.msg);

      if(result.data.goto == 'balance'){
        App.showSuccess(result.msg);
       
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/user/index',
            })
          }, 500);
        
       
        
      }else if(result.data.goto == 'goods'){
        App.globalData.goods_tab = 'douyin'
        wx.navigateTo({
          url: '/pages/goods/index?goods_id='+result.data.goods_id,
        })
      }else{
        wx.navigateTo({
          url: '/pages/user/coupon/coupon',
        })
      }
    },function(){
      wx.hideLoading()
    },function(){
      wx.hideLoading()
    });
  },
});